package licode.unisop.authcenter.application.executor;

import cn.hutool.core.util.StrUtil;
import licode.unisop.authcenter.exception.CenterErrorCode;
import licode.unisop.authcenter.utils.CheckUtil;
import licode.unisop.platform.client.api.SiPlatformAuthService;
import licode.unisop.platform.client.api.SiPlatformService;
import licode.unisop.platform.client.info.PlatformSaveIn;
import licode.unisop.provider.info.SiAuthPlatToUserIn;
import licode.unisop.provider.info.SiPlatformId;
import licode.unisop.provider.vo.SiPlatform;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 定义统一认证平台中心平台相关接口
 *
 * @author licode
 */
@Service
public class CenterPlatformExecutor {
    @Resource
    private SiPlatformService siPlatformService;

    @Resource
    private SiPlatformAuthService siPlatformAuthService;

    public void updateCache(SiPlatformId platId) {
        siPlatformAuthService.updateCache(platId);
    }

    public void add(PlatformSaveIn saveIn) {
        checkPlatform(saveIn);
        
        siPlatformService.addPlatform(saveIn);
    }

    public void update(PlatformSaveIn saveIn) {
        checkPlatform(saveIn);

        siPlatformService.updatePlatform(saveIn);
    }

    public void grantPlatform(SiAuthPlatToUserIn item) {
        siPlatformService.grantPlatform(item);
    }

    public void checkPlatform(PlatformSaveIn saveIn) {
        SiPlatform item = saveIn.getPlatform();
        CheckUtil.checkState(item.getState());

        if (StrUtil.isBlank(item.getId())) {
            throw CenterErrorCode.WRONG_TARGET_CLIENT.buildException();
        }

        if (StrUtil.isBlank(item.getTicketUrl())) {
            item.setTicketUrl("");
        }

        if (StrUtil.isBlank(item.getTenantId())) {
            item.setTenantId("");
        }

        if (StrUtil.isBlank(item.getRealmId())) {
            item.setRealmId("");
        }

        if (StrUtil.isBlank(item.getHomeUrl())) {
            item.setHomeUrl("");
        }

        item.setUpdateTime(LocalDateTime.now());
    }
}
